#include <iostream>
#include <pthread.h>
#include <vector>
#include <string>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *SlaverCore(void *args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        // 1.加锁
        pthread_mutex_lock(&mutex);
        // 2.一般条件变量在加锁与解锁之间使用
        pthread_cond_wait(&cond,&mutex); // &mutex 释放自己持有的锁
        std::cout << "当前别唤醒的线程是：" << name << std::endl;
        // 3.解锁
        pthread_mutex_unlock(&mutex);
    }
}
void *MasterCore(void *args)
{
    sleep(3);
    std::cout << "master 开始工作..." << std::endl;
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_cond_signal(&cond); // 唤醒一个队列首部的线程
        //pthread_cond_broadcast(&cond); // 唤醒一个队列中所有线程
        std::cout << "master 唤醒一个线程..." << std::endl;
        sleep(1); 
    } 
}

void StartMaster(std::vector<pthread_t> *tids)
{
    pthread_t tid;
    int n = pthread_create(&tid,nullptr,MasterCore,(void*)"Master Thread");
    if(n == 0)
    {
        std::cout << "create master success" << std::endl;
    }
    tids->emplace_back(tid);
}
void StartSlaver(std::vector<pthread_t> *tids,int threadnum = 1)
{
    for(int i = 0;i < threadnum;i++)
    {
        char *name = new char[64];
        snprintf(name,64,"slaver-%d",i + 1);
        pthread_t tid;
        int n = pthread_create(&tid,nullptr,SlaverCore,name);
        if(n == 0)
        {
            std::cout << "create slaver success" << std::endl;
            tids->emplace_back(tid);
        }
    }
}
void WaitThread(std::vector<pthread_t> &tids)
{
    for(auto &tid : tids)
    {
        pthread_join(tid,nullptr);
    }
}

int main()
{
    std::vector<pthread_t> tids;
    StartMaster(&tids);
    StartSlaver(&tids,3);
    WaitThread(tids);

    return 0;
}
